﻿using OSGeo.OGR;
using OSGeo.GDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;

namespace MyCustomTool
{
    internal class Program
    {
        static void Main(string[] args)
        {
            GdalConfiguration.ConfigureOgr();
            GdalConfiguration.ConfigureGdal();
            Gdal.SetConfigOption("GDAL_DATA", @"gdal\data");
            Gdal.SetConfigOption("SHAPE_ENCODING", "UTF-8");
            Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");

            //ShpMerge();
            //SetDEM();
            //WriteDEM();
            //SetPipePointHeight();
            ReadDEM();
        }

        static void ShpMerge()
        {
            DirectoryInfo path = new DirectoryInfo(@"D:\04-Data\长春市_建筑轮廓");
            FileInfo[] files = path.GetFiles("*.shp");

            FileShp input = new FileShp(files[0].FullName, null);
            FileShp output = new FileShp(@"D:\04-Data\result.shp", input);

            for (int i = 0; i < files.Length; i++)
            {
                Console.WriteLine("开始：" + i);
                input = new FileShp(files[i].FullName, null);

                for (long j = 0; j < input.FeatureCount; j++)
                {
                    Console.WriteLine(j);
                    input.GetFeatureData(j);
                    output.SetFeatureData(input.FieldInfo, input.Geometry);
                }
            }
        }

        static void SetDEM()
        {
            Dataset ds = Gdal.Open(@"D:\04-Data\长春市_高程\吉林省_高程_Level_12.tif", Access.GA_ReadOnly);

            double[] gt = new double[6];
            ds.GetGeoTransform(gt);

            Band demband = ds.GetRasterBand(1);
            int XSize = ds.RasterXSize;
            int YSize = ds.RasterYSize;
            double[] databuf = new double[XSize * YSize];
            demband.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, databuf, ds.RasterXSize, ds.RasterYSize, 0, 0);

            FileShp input = new FileShp(@"D:\04-Data\长春市_建筑轮廓_结果\result_error.shp", null);
            FileShp output = new FileShp(@"D:\04-Data\长春市_建筑轮廓_结果\result_height.shp", input);

            for (long j = 0; j < input.FeatureCount; j++)
            {
                Console.WriteLine(j);
                input.GetFeatureData(j);

                // 创建要素
                output.FeatureDefn = output.Layer.GetLayerDefn();
                Feature feature = new Feature(output.FeatureDefn);

                // 添加属性表
                for (int field = 0; field < output.FieldHead.Count; field++)
                {
                    FieldDefn fieldDefn = output.FeatureDefn.GetFieldDefn(field);
                    FieldType type = fieldDefn.GetFieldType();

                    if (fieldDefn.GetName() == "Floor")
                    {
                        int[] position = TransCoorToRowCol(gt, Convert.ToDouble(input.FieldInfo[3]), Convert.ToDouble(input.FieldInfo[4]));
                        double height = databuf[position[1] * XSize + position[0]];
                        feature.SetField(5, height);
                    }
                    else
                    {
                        switch (type)
                        {
                            case FieldType.OFTString:
                                feature.SetField(field, input.FieldInfo[field]);
                                break;
                            case FieldType.OFTReal:
                                feature.SetField(field, input.FieldInfo[field]);
                                break;
                            case FieldType.OFTInteger:
                                feature.SetField(field, input.FieldInfo[field]);
                                break;
                            default:
                                feature.SetField(field, input.FieldInfo[field]);
                                break;
                        }
                    }
                }

                // 添加图形
                feature.SetGeometry(input.Geometry);

                // 添加要素
                output.Layer.CreateFeature(feature);
            }
        }

        static void WriteDEM()
        {
            FileShp input = new FileShp(@"D:\04-Data\香格里拉\香格里拉\Rectangle_#14_建筑轮廓.shp", null);
            FileShp output = new FileShp(@"D:\04-Data\香格里拉\xianggelila.shp", input);

            StreamReader txt = new StreamReader(@"C:\Users\shenzhiqiang\Desktop\height.txt", Encoding.GetEncoding("GB2312"));

            for (long j = 0; j < input.FeatureCount; j++)
            {
                Console.WriteLine(j);
                input.GetFeatureData(j);

                // 创建要素
                output.FeatureDefn = output.Layer.GetLayerDefn();
                Feature feature = new Feature(output.FeatureDefn);

                // 添加属性表
                for (int field = 0; field < output.FieldHead.Count; field++)
                {
                    FieldDefn fieldDefn = output.FeatureDefn.GetFieldDefn(field);
                    FieldType type = fieldDefn.GetFieldType();

                    if (fieldDefn.GetName() == "elevation")
                    {
                        string height = txt.ReadLine();
                        feature.SetField(5, height);
                    }
                    else
                    {
                        switch (type)
                        {
                            case FieldType.OFTString:
                                feature.SetField(field, input.FieldInfo[field]);
                                break;
                            case FieldType.OFTReal:
                                feature.SetField(field, input.FieldInfo[field]);
                                break;
                            case FieldType.OFTInteger:
                                feature.SetField(field, input.FieldInfo[field]);
                                break;
                            default:
                                feature.SetField(field, input.FieldInfo[field]);
                                break;
                        }
                    }
                }

                // 添加图形
                feature.SetGeometry(input.Geometry);

                // 添加要素
                output.Layer.CreateFeature(feature);
            }
        }

        static void SetPipePointHeight()
        {
            FileShp input = new FileShp(@"D:\04-Data\长天20230307\cctrq_pointPoint.shp", null);

            StreamReader txt = new StreamReader(@"C:\Users\shenzhiqiang\Desktop\height.txt", Encoding.GetEncoding("GB2312"));

            for (long j = 0; j < input.FeatureCount; j++)
            {
                Console.WriteLine(j);
                Feature feature = input.Layer.GetFeature(j);
                string height = txt.ReadLine();
                Double elevation = Convert.ToDouble(height) - 1.8;
                feature.SetField(23, elevation);
                input.Layer.SetFeature(feature);
            }
        }

        static int[] TransCoorToRowCol(double[] dGeoTrans, double lng, double lat)
        {
            double dTemp = dGeoTrans[1] * dGeoTrans[5] - dGeoTrans[2] * dGeoTrans[4];
            double col = (dGeoTrans[5] * (lng - dGeoTrans[0]) - dGeoTrans[2] * (lat - dGeoTrans[3])) / dTemp + 0.5;
            double row = (dGeoTrans[1] * (lat - dGeoTrans[3]) - dGeoTrans[4] * (lng - dGeoTrans[0])) / dTemp + 0.5;
            return new int[] { Convert.ToInt32(Math.Floor(row)), Convert.ToInt32(Math.Floor(col)) };
        }

        static double[] TransRowColToCoor(double[] dGeoTrans, int Row, int Col)
        {
            double X = dGeoTrans[0] + Col * dGeoTrans[1] + Row * dGeoTrans[2];
            double Y = dGeoTrans[3] + Col * dGeoTrans[4] + Row * dGeoTrans[5];
            return new double[] { X, Y };
        }

        static void ReadDEM()
        {
            MySqlConnection conn = null;
            MySqlCommand comm = null;
            MySqlDataReader dr = null;
            conn = new MySqlConnection("Database = test;Server = localhost;Port = 3306;Password = shenzhiqiang;UserID = root;charset = utf8mb4");
            conn.Open();
            comm = new MySqlCommand("select * from test", conn);
            dr = comm.ExecuteReader();
            while (dr.Read())
            {
                Console.WriteLine(dr.GetString("lon") + "----" + dr.GetString("lat"));
            }
            dr.Close();

            Dataset ds = Gdal.Open(@"D:\04-Data\吉林省高程\吉林省_高程_Level_12.tif", Access.GA_ReadOnly);

            double[] gt = new double[6];
            ds.GetGeoTransform(gt);

            Band demband = ds.GetRasterBand(1);
            int colSize = ds.RasterXSize;
            int rowSize = ds.RasterYSize;
            double[] databuf = new double[rowSize * colSize];
            demband.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, databuf, ds.RasterXSize, ds.RasterYSize, 0, 0);

            for (int i = 0; i < colSize; i++)
            {

                String sql = "";
                for (int j = 0; j < rowSize; j++)
                {
                    double[] coor = TransRowColToCoor(gt, j, i);
                    double value = databuf[j * colSize + i];
                    sql += "insert jilin_grid(MIN_LNG,MIN_LAT,MAX_LNG,MAX_LAT,HEIGHT) values (" + (coor[0] - gt[1]) + "," + coor[1] + "," + coor[0] + "," + (coor[1] + gt[5]) + "," + value + ");";
                }
                comm = new MySqlCommand(sql, conn);
                int rows = comm.ExecuteNonQuery();
                Console.WriteLine("第" + i + "列，成功" + rows + "条");
            }
            conn.Close();
        }
    }
}
